#!/bin/sh

set +xe
project=$1

# 注入环境变量
. $CI_SHELL_PATH/scripts/build-env-generate.sh

# todo: 仅在prod/prl时打包镜像
export DOCKER_IMAGE_NAME=$CI_PROJECT_NAME-$CI_COMMIT_BRANCH
export DOCKER_IMAGE_PREFIX="shjrccr.ccs.tencentyun.com/qtrade-fe"
cat ${DOCKER_PASSWORD} | docker login shjrccr.ccs.tencentyun.com -u=${DOCKER_USER_NAME} --password-stdin

echo "${DOCKER_PASSWORD}" > .docker_auth
cat .docker_auth | docker login shjrccr.ccs.tencentyun.com -u=${DOCKER_USER_NAME} --password-stdin

echo "**/*.map" >> ./dist/.dockerignore
docker build -t "${DOCKER_IMAGE_PREFIX}/${DOCKER_IMAGE_NAME}:latest" \
  -t "${DOCKER_IMAGE_PREFIX}/${DOCKER_IMAGE_NAME}:${ROLLBACK_VERSION_ID}" \
  .
docker push "${DOCKER_IMAGE_PREFIX}/${DOCKER_IMAGE_NAME}:latest"
docker push "${DOCKER_IMAGE_PREFIX}/${DOCKER_IMAGE_NAME}:${ROLLBACK_VERSION_ID}"

# remove old images
docker image ls | grep "${DOCKER_IMAGE_PREFIX}/${DOCKER_IMAGE_NAME}:*" | awk '!/latest|<none>/ { print $1":"$2}' | xargs -n1 docker image rm